package com.hh.game.service.gateway.filter.ip;

import cn.hutool.core.collection.ConcurrentHashSet;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class IPContainer {
    private static Map<String, OutQpsCount> outQpsCloseIP = new ConcurrentHashMap<>();
    private static Set<String> BLACK_IP = new ConcurrentHashSet<>();

    public static void addBlackIP(String ip){
        BLACK_IP.add(ip);
    }

    public static boolean isBlackIP(String ip){
        return BLACK_IP.contains(ip);
    }

    public static int addOutQpsCloseIP(String ip) {
        OutQpsCount count = outQpsCloseIP.get(ip);
        if (count == null) {
            count = new OutQpsCount();
            outQpsCloseIP.put(ip, count);
        }
        return count.addAndGet();
    }

    public static int getOutQpsCloseIPCount(String ip) {
        OutQpsCount count = outQpsCloseIP.get(ip);
        if (count == null) {
            return 0;
        }
        return count.count.get();
    }

    static class OutQpsCount{
        private long time;
        private AtomicInteger count;

        public int addAndGet(){
            long now = System.currentTimeMillis();
            if(now - time > 1000 * 60){
                time = now;
                count.set(1);
                return 1;
            }
            return count.addAndGet(1);
        }

        public OutQpsCount() {
            time = System.currentTimeMillis();
            count = new AtomicInteger(1);
        }
    }

}
